<?php
$key = $_GET['key'];
//配置信息
$conn_params = array(
    'host' => 'fungo.tpddns.cn',
    'port' => '5673',
    'login' => 'admin',
    'password' => '123456',
);
$e_name = 'client_platform'; //交换机名
$q_name = $key; //队列名
$k_route = $key; //路由key
//创建连接和channel
$conn = new AMQPConnection($conn_params);

if (!$conn->connect()) {
    die("Cannot connect to the broker!\n");
}
$channel = new AMQPChannel($conn);
//var_dump($$channel);
//创建交换机
$ex = new AMQPExchange($channel);
$ex->setName($e_name);
$ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型
$ex->setFlags(AMQP_DURABLE); //持久化
//echo "Exchange Status:".$ex->declareExchange()."\n";

//创建队列
$q = new AMQPQueue($channel);
$q->setName($q_name);
$q->setFlags(AMQP_DURABLE); //持久化
//echo "Message Total:";
$q->declareQueue();
//绑定交换机与队列，并指定路由键
//echo 'Queue Bind: ';
$q->bind($e_name, $k_route);
//阻塞模式接收消息
//echo "Message:\n";


while(true){
    try {
        getConsume($q);
    }catch (Exception $e) {
        //echo 'error:';
        //print_r($e->getMessage());
        break;
    }
}
$conn->disconnect();
/**
 * 消费回调函数
 * 处理消息
 */
function processMessage($envelope, $queue) {

    $data = json_decode($envelope->getBody(),true);
     
    if(!empty($data['list'])){
        $data_1['uuid'] = $data['uuid'];
        $data_1['list'] = '';
        foreach ($data['list'] as $key => $value) {
            $data_1['list'][] = $value['bigPic'];
        }
        $data_1 = json_encode($data_1);
    }else{
        $data_1 = '';
    }
    $datas['msg'] = urlencode($data_1);
    //var_dump($datas);
    $url = 'http://'.$_SERVER['SERVER_NAME'].'/api/receive';
    https_post($url,$datas);
    //echo $data['msg']."\n"; //处理消息
    $queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答
    //return $data['msg'];
}

function getConsume($queue){
    $tag = uniqid() . microtime(true);
    $queue->consume('processMessage', AMQP_AUTOACK,$tag); //自动ACK应答
    $queue->cancel($tag);
}


function https_post($url,$data){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url); 
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    
    if (curl_errno($curl)) {
       return 'Errno'.curl_error($curl);
    }
    curl_close($curl);
    //return $result;
}
?>